/*
Created by Borui Wang (bwang29@wisc.edu)
March, 2012, GoCuro
util.js
*/


JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};



function webUtil(){
	
	
	this.makeGenericGetRequest = function(targetUrl, responseFunction, errorCode, serviceDesc)
	{				
		var fullUrl = targetUrl;			
		var params = "";
		$.ajax({
			type: "GET",
			url: fullUrl,
			data: params,
			dataType: "jsonp", //jsonp or json should both be find
			timeout: 40000, // in milliseconds
			success: responseFunction,
			error: function(request, status, err) {
				if(status == "timeout") {
					this.handleError(errorCode,serviceDesc);
				}
			}
		});
	};
	
	
	
	this.makeGenericPOSTRequest = function(targetUrl, postInstance, responseFunction,errorCode,serviceDesc)
	{
		var params = postInstance;	
		
		//format: params.x = "y";	
		$.ajax({
			type: "POST",
			url: targetUrl,
			data: postInstance,
			dataType: "jsonp", //jsonp or json should both be fine
			timeout: 40000, // in milliseconds
			success: responseFunction,
			error: function(request, status, err) {
				if(status == "timeout") {
					handleError(errorCode,serviceDesc);
				}
			}
		});
	};
	
	this.parseJSONResponse = function(response)
	{	
		var jsonResponse = eval("(" + response + ")"); //ok!				
		return jsonResponse;
	};
	
	this.toParam = function(obj)
	{
		str = "";
		for(property in obj)
		{
			str += property+"="+ obj[property]+"&";
		}
		return str;
	};
}


function setCookie(c_name,value,exdays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++)
	{
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name)
		{
		return unescape(y);
		}
	}
	return "Invalid";
}

this.handleError = function(errorCode,serviceDesc)
{
	alert("Connection timeout, please check if you're connected to the internet");
	window.location.reload();
};